package main

// <-------------------------------- RabbitMQ --------------------------------------------->
import (
	"bytes"
	"encoding/json"
	"fmt"

	"github.com/streadway/amqp"
)

/*
	功能：amqp转发任务
	参数：1. http_url amqp转发地址
		2.  map_user_del 去掉rpc_exclude 含有的信息的map
*/
func AmqpWork(http_url string, map_user_del map[string]string) {

	// map 转换成 json
	df := bytes.NewBuffer([]byte{}) // 我们转换程的json
	jsonEncoder := json.NewEncoder(df)
	jsonEncoder.SetEscapeHTML(false)
	jsonEncoder.Encode(map_user_del)

	dataBytes := df.Bytes()

	rabi, err := New("172.18.130.3")
	if err != nil {
		fmt.Println("new is wrong: ", err)
		return
	}
	test := rabi.PublishQueue("eslapi.goods.update", dataBytes)
	if test == nil {
		// //fmt.Fprintf(res, "status:%d, method:%s, pageNo:%s, message:%s", 200, "update", map_user_del["pageNo"], message)
	}

}

type Rabbitmq struct {
	conn *amqp.Connection
	err  error
}

/*
	功能：创建rabbitmq连接
	参数：1. ip   rabbitmq的ip地址
	返回值 1. rabbitmq  rabbitmq连接
		  2  返回错误信息
*/
func New(ip string) (*Rabbitmq, error) {
	amqps := fmt.Sprintf("amqp://eslerp:eslerp@%s:5672/eslerp", ip)
	conn, err := amqp.Dial(amqps)
	if err != nil {
		return nil, err
	}
	rabbitmq := &Rabbitmq{
		conn: conn,
	}
	return rabbitmq, nil
}

/*
	功能：向Rabbitmq发送信息
	参数： 1. id  routing key
		  2. body  要发送的json byte数据
	返回值： 成功返回空
*/
func (rabbitmq *Rabbitmq) PublishQueue(id string, body []byte) error {
	ch, err := rabbitmq.conn.Channel()
	defer ch.Close()
	if err != nil {
		return err
	}
	err = ch.Publish(
		"amq.direct", // exchange
		id,           // routing key
		false,        // mandatory
		false,
		amqp.Publishing{
			DeliveryMode: amqp.Persistent,
			ContentType:  "text/plain",
			Body:         (body),
		})
	if err != nil {
		return err
	}

	return nil
}
